<template>
  <div class="work-calendar">
    <!-- 顶部工具栏 -->
    <div class="calendar-header">
      <div class="date-selector">
        <el-button icon="el-icon-arrow-left" type="text" @click="prevMonth"> 上个月 </el-button>
        <span class="current-date">{{ currentYear }}年{{ currentMonth }}月</span>
        <el-button icon="el-icon-arrow-right" type="text" @click="nextMonth"> 下个月 </el-button>
      </div>

      <div class="view-controls">
        <el-button type="primary" @click="saveSchedule">保存设置</el-button>
        <el-button type="default" @click="applyToAllCenters">应用到所有工作中心</el-button>
        <el-button type="default" @click="resetToDefaults">恢复默认设置</el-button>
      </div>
    </div>

    <!-- 日历头部（星期） -->
    <div class="calendar-weekdays">
      <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
    </div>

    <!-- 日历主体 -->
    <div class="calendar-days">
      <div
        v-for="(day, index) in calendarDays"
        :key="index"
        :class="{
          'other-month': day.month !== currentMonth,
          'today': isToday(day),
          'holiday': isHoliday(day),
          'weekend': isWeekend(day),
          'selected': isSelected(day)
        }"
        @click="selectDate(day)"
      >
        <div class="day-number">{{ day.date }}</div>
        <div v-if="day.status" class="day-status">
          {{ getStatusLabel(day.status) }}
        </div>
      </div>
    </div>

    <!-- 出勤模式设置面板 -->
    <div class="schedule-settings">
      <h3>出勤模式设置</h3>

      <el-radio-group v-model="selectedStatus">
        <el-radio label="normal">正常出勤</el-radio>
        <el-radio label="half">半天出勤</el-radio>
        <el-radio label="off">休息</el-radio>
        <el-radio label="holiday">节假日</el-radio>
      </el-radio-group>

      <el-button type="primary" @click="applyStatusToSelected">应用到所选日期</el-button>
      <el-button type="default" @click="clearSelection">清除选择</el-button>
    </div>

    <!-- 工作中心选择器 -->
    <div class="work-centers">
      <h3>工作中心</h3>
      <el-select v-model="selectedCenter" multiple placeholder="请选择工作中心">
        <el-option v-for="center in workCenters" :key="center.id" :label="center.name" :value="center.id"></el-option>
      </el-select>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

// 当前日期
const currentDate = new Date();
const currentYear = ref(currentDate.getFullYear());
const currentMonth = ref(currentDate.getMonth() + 1);

// 星期显示
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

// 工作中心数据
const workCenters = ref([
  { id: 1, name: '总部' },
  { id: 2, name: '分部A' },
  { id: 3, name: '分部B' },
  { id: 4, name: '分部C' }
]);

// 当前选择的工作中心
const selectedCenter = ref([1]);

// 出勤状态
const statusTypes = {
  normal: { label: '出勤', color: '#67C23A' },
  half: { label: '半天', color: '#E6A23C' },
  off: { label: '休息', color: '#909399' },
  holiday: { label: '假日', color: '#F56C6C' }
};

// 当前选择的状态
const selectedStatus = ref('normal');

// 选中的日期
const selectedDates = ref([]);

// 日历数据
const calendarDays = ref([]);

// 默认节假日
const defaultHolidays = ref([
  { year: 2023, month: 1, day: 1, name: '元旦' },
  { year: 2023, month: 1, day: 2, name: '元旦假期' },
  { year: 2023, month: 5, day: 1, name: '劳动节' },
  { year: 2023, month: 10, day: 1, name: '国庆节' }
]);

// 初始化日历数据
const generateCalendar = () => {
  // 清空日历数据
  calendarDays.value = [];

  // 获取当月第一天
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1);
  // 获取当月最后一天
  const lastDay = new Date(currentYear.value, currentMonth.value, 0);

  // 获取当月第一天是星期几 (0-6)
  const firstDayOfWeek = firstDay.getDay();

  // 获取上个月的最后几天
  const prevMonthLastDay = new Date(currentYear.value, currentMonth.value - 1, 0);
  const prevMonthDaysToShow = firstDayOfWeek;

  // 获取当月的天数
  const daysInMonth = lastDay.getDate();

  // 获取下个月的前几天
  const nextMonthDaysToShow = 42 - (prevMonthDaysToShow + daysInMonth); // 6行7列 = 42个格子

  // 添加上个月的最后几天
  for (let i = prevMonthDaysToShow; i > 0; i--) {
    const date = prevMonthLastDay.getDate() - i + 1;
    const month = currentMonth.value - 1 === 0 ? 12 : currentMonth.value - 1;
    const year = month === 12 ? currentYear.value - 1 : currentYear.value;

    calendarDays.value.push({
      year,
      month,
      date,
      isCurrentMonth: false,
      status: getDayStatus(year, month, date)
    });
  }

  // 添加当月的所有天
  for (let i = 1; i <= daysInMonth; i++) {
    calendarDays.value.push({
      year: currentYear.value,
      month: currentMonth.value,
      date: i,
      isCurrentMonth: true,
      status: getDayStatus(currentYear.value, currentMonth.value, i)
    });
  }

  // 添加下个月的前几天
  for (let i = 1; i <= nextMonthDaysToShow; i++) {
    const month = currentMonth.value + 1 > 12 ? 1 : currentMonth.value + 1;
    const year = month === 1 ? currentYear.value + 1 : currentYear.value;

    calendarDays.value.push({
      year,
      month,
      date: i,
      isCurrentMonth: false,
      status: getDayStatus(year, month, i)
    });
  }
};

// 获取日期状态
const getDayStatus = (year, month, day) => {

  // 检查是否为默认节假日
  const isHoliday = defaultHolidays.value.some(h =>
    h.year === year && h.month === month && h.day === day
  );

  if (isHoliday) {
    return 'holiday';
  }

  // 检查是否为周末
  const date = new Date(year, month - 1, day);
  const dayOfWeek = date.getDay();

  if (dayOfWeek === 0 || dayOfWeek === 6) {
    return 'off';
  }

  // 默认工作日
  return 'normal';
};

// 判断是否为今天
const isToday = (day) => {
  return (
    day.year === currentDate.getFullYear() &&
    day.month === currentDate.getMonth() + 1 &&
    day.date === currentDate.getDate()
  );
};

// 判断是否为周末
const isWeekend = (day) => {
  const date = new Date(day.year, day.month - 1, day.date);
  const dayOfWeek = date.getDay();
  return dayOfWeek === 0 || dayOfWeek === 6;
};

// 判断是否为节假日
const isHoliday = (day) => {
  return defaultHolidays.value.some(h =>
    h.year === day.year && h.month === day.month && h.day === day.date
  );
};

// 判断日期是否被选中
const isSelected = (day) => {
  return selectedDates.value.some(d =>
    d.year === day.year && d.month === day.month && d.date === day.date
  );
};

// 获取状态标签
const getStatusLabel = (status) => {
  return statusTypes[status]?.label || '';
};

// 选择日期
const selectDate = (day) => {
  console.log(day,'*************')
  // 不允许选择非当月的日期
  if (!day.isCurrentMonth) return;

  const index = selectedDates.value.findIndex(d =>
    d.year === day.year && d.month === day.month && d.date === day.date
  );

  if (index === -1) {
    // 添加到选中列表
    selectedDates.value.push({
      year: day.year,
      month: day.month,
      date: day.date
    });
  } else {
    // 从选中列表移除
    selectedDates.value.splice(index, 1);
  }
};

// 应用状态到选中的日期
const applyStatusToSelected = () => {
  if (selectedDates.value.length === 0) {
    ElMessage.warning('请先选择日期');
    return;
  }

  // 更新日历数据中选中日期的状态
  calendarDays.value = calendarDays.value.map(day => {
    if (isSelected(day)) {
      return {
        ...day,
        status: selectedStatus.value
      };
    }
    return day;
  });

  // 清空选中状态
  selectedDates.value = [];
};

// 清除选择
const clearSelection = () => {
  selectedDates.value = [];
};

// 保存设置
const saveSchedule = () => {
  // 这里应该调用API保存数据
  ElMessage.success('出勤设置已保存');
};

// 应用到所有工作中心
const applyToAllCenters = () => {
  // 这里应该调用API将当前设置应用到所有工作中心
  ElMessage.success('已应用到所有工作中心');
};

// 恢复默认设置
const resetToDefaults = () => {
  // 重新生成日历数据，恢复默认状态
  generateCalendar();
  ElMessage.success('已恢复默认设置');
};

// 切换到上个月
const prevMonth = () => {
  if (currentMonth.value === 1) {
    currentYear.value--;
    currentMonth.value = 12;
  } else {
    currentMonth.value--;
  }
  generateCalendar();
  selectedDates.value = [];
};

// 切换到下个月
const nextMonth = () => {
  if (currentMonth.value === 12) {
    currentYear.value++;
    currentMonth.value = 1;
  } else {
    currentMonth.value++;
  }
  generateCalendar();
  selectedDates.value = [];
};

// 初始化
onMounted(() => {
  generateCalendar();
});
</script>

<style scoped>
.work-calendar {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.date-selector {
  display: flex;
  align-items: center;
}

.current-date {
  font-size: 18px;
  font-weight: bold;
  margin: 0 10px;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  margin-bottom: 10px;
}

.weekday {
  text-align: center;
  font-weight: bold;
  padding: 8px;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
  margin-bottom: 20px;
}

.calendar-days > div {
  min-height: 100px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.calendar-days > div:hover {
  background-color: #f5f7fa;
}

.other-month {
  color: #c0c4cc;
}

.today {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

.holiday {
  background-color: #fef0f0;
  border-color: #fde2e2;
}

.weekend {
  background-color: #f5f7fa;
}

.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.day-number {
  font-weight: bold;
  margin-bottom: 8px;
}

.day-status {
  display: inline-block;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
  margin-bottom: 4px;
}

.status-normal {
  background-color: #e1f3d8;
  color: #67c23a;
}

.status-half {
  background-color: #faecd8;
  color: #e6a23c;
}

.status-off {
  background-color: #f4f4f5;
  color: #909399;
}

.status-holiday {
  background-color: #fde2e2;
  color: #f56c6c;
}

.schedule-settings,
.work-centers {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.schedule-settings h3,
.work-centers h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
}

.radio-group {
  margin-bottom: 15px;
}
</style>
